﻿using UnityEngine.UIElements;

namespace winS.UnityEditor.UIElement
{
    /// <summary>
    /// Editor field for display and edit Text.
    /// </summary>
    public class TextField : EditorField<string>
    {
        public bool multiline { get => textElement.style.whiteSpace == WhiteSpace.Normal; set => textElement.style.whiteSpace = value ? WhiteSpace.Normal : WhiteSpace.NoWrap; }
        public bool allowNewline { get => textField.multiline; set => textField.multiline = multiline = value; }
        public bool enableRichText { get => textElement.enableRichText; set => textElement.enableRichText = value; }

        public VisualElement textInput => textField.ElementAt(0);
        public TextElement textElement => textInput.Q<TextElement>();

        protected readonly UnityEngine.UIElements.TextField textField;

        internal TextField(ElementFactory elementFactory) : base(elementFactory)
        {
            Add(textField = new UnityEngine.UIElements.TextField());
            textField.style.whiteSpace = WhiteSpace.Normal;
            textElement.style.flexShrink = 1f;
            textElement.style.whiteSpace = WhiteSpace.NoWrap;

            textField.style.SetUnityFontDefinition(PackageAssets.FontSet.microsoftYahei);
            EditorElementUtility.ApplySubFieldStyle(textField);
            textField.RegisterCallback<ClickEvent>(ClickCallback);
            textField.RegisterValueChangedCallback(OnValueChangedCallback);
        }

        public override void SetValueWithoutNotify(string value)
        {
            base.SetValueWithoutNotify(value);
            textField.SetValueWithoutNotify(value);
        }

        protected override void SetValue(string value)
        {
            base.SetValue(value);
            textField.SetValueWithoutNotify(value);
        }

        private void ClickCallback(ClickEvent clickEvent)
        {
            clickEvent.StopImmediatePropagation();
        }
        private void OnValueChangedCallback(ChangeEvent<string> changeEvent)
        {
            base.SetValue(changeEvent.newValue);
        }
    }
}